package kd.xkqj.unittest.plugin.action;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.openapi.ui.Messages;
import kd.xkqj.unittest.plugin.CodeGenerator;
import kd.xkqj.unittest.plugin.model.JavaFileInfo;
import kd.xkqj.unittest.plugin.JavaFileParser;
import kd.xkqj.unittest.plugin.model.JavaMethodInfo;
import kd.xkqj.unittest.plugin.setting.PluginSettingsService;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static kd.xkqj.unittest.plugin.CodeGenerator.completeAllTestMethod;
import static kd.xkqj.unittest.plugin.action.AnActionHelper.*;
import static kd.xkqj.unittest.plugin.model.JavaFileInfo.isExistTargetMethod;

/**
 * @description: 创建模版文件动作
 * @author feng_jun_peng
 * @create 2024-12-17 16:53
 * @version 1.0
 */
public class FileRightClickAction extends AnAction {

    /** 为了避免UI线程卡住，新版本IDEA对于update事件有时间要求，因此不再对.java文件类型进行判断

        @Override
public @NotNull ActionUpdateThread getActionUpdateThread() {
    // 根据实际需求返回 EDT 或 BGT
    return ActionUpdateThread.BGT;
}
@Override
public void update(@NotNull AnActionEvent e) {
    // 获取当前选中的文件
    PsiFile psiFile = e.getData(PlatformDataKeys.PSI_FILE);
    // 检查是否为 Java 类文件
    boolean isJavaFile = psiFile != null && psiFile.getName().endsWith(".java");
    // 控制动作是否可用
    e.getPresentation().setEnabledAndVisible(isJavaFile);
}
     */

    /**
     * description: 创建单元测试路径
     * @author: feng_jun_peng
     * @create: 2024-12-19 11:14
     * @param e:
     * @return: java.lang.String
     */
    private String createTestDirectory(AnActionEvent e) {
        var path = AnActionHelper.getCurrentFilePath(e);

        path = path.replace("PsiDirectory:", "").replace("\\src\\main", "\\src\\test");

        File file = new File(path);
        // 获取文件所在的目录
        File directory = file.getParentFile();

        if (!directory.exists()) {
            directory.mkdirs();//创建目录
        }
        return directory.toString();
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) {
            Messages.showErrorDialog("找不到项目！", "Error");
            return;
        }

        PsiFile currentFile = e.getData(PlatformDataKeys.PSI_FILE);
        if (currentFile == null) {
            Messages.showErrorDialog("没有选择任何文件！", "Error");
            return;
        }

        if (currentFile.getContainingDirectory().toString().indexOf("\\src\\main") == -1) {
            Messages.showErrorDialog("当前java文件不是标准的\\src\\main路径！", "Error");
            return;
        }

        var newDirectoryPath = createTestDirectory(e);
        if (newDirectoryPath == null) {
            return;
        }

        PluginSettingsService settingsService = PluginSettingsService.getInstance();
        var state = settingsService.getState();

        var autoNewClassName = currentFile.getOriginalFile().getName().replace(".java", "Test.java");
        String newClassName = autoNewClassName;

        if (state.showConfirm) {
            newClassName = Messages.showInputDialog("请输入单元测试类名：", "创建或更新单元测试类：", Messages.getQuestionIcon(), autoNewClassName, null);

            if (newClassName == null)
                return;

            newClassName = newClassName.trim();
            if (newClassName.isEmpty()) {
                Messages.showErrorDialog("单元测试类名不能为空！", "Error");
                return;
            }

            if (newClassName.indexOf(".java") == -1) {
                newClassName += ".java";
            }
        }

        var sourcePath = getCurrentFilePath(e);
        var targetPath = newDirectoryPath + "\\" + newClassName;

        var sourceJavaFileInfo = JavaFileParser.parseJavaFile(sourcePath);

        // 检查文件是否存在
        if (!new File(targetPath).exists()) {
            // 创建Java文件，并按模版填充信息
            CodeGenerator.genNewUnitTestFile(targetPath, sourceJavaFileInfo, newClassName);
            showNotification(project, "成功创建单元测试类", newClassName, 3000);
        } else {
            var targetJavaFileInfo = JavaFileParser.parseJavaFile(targetPath);
            completeAllTestMethod(project, targetPath, sourceJavaFileInfo, targetJavaFileInfo);
        }
        reloadFileFromDisk(project, targetPath, -1);
    }

}
